package com.acegear.horizon.domain.events.handlers;

import com.acegear.horizon.domain.events.DefaultSettingsModifiedEvent;
import com.acegear.horizon.domain.models.jpa.DefaultSettings;
import com.acegear.horizon.domain.repository.jpa.DefaultSettingsRepository;
import com.acegear.horizon.vendor.ons.ONSConsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;

/**
 * Created by guoweike on 17/3/23.
 */
@Component
public class DefaultSettingsHandler {

    @Autowired
    private DefaultSettingsRepository defaultSettingsRepository;
    @Autowired
    private ONSConsumer consumer;

    @PostConstruct
    public void defaultSettingsModifiedONS() {
        consumer.consume(DefaultSettingsModifiedEvent.class, this::defaultSettingsModified);
    }

    //默认头像背景修改
    @Transactional
    public void defaultSettingsModified(DefaultSettingsModifiedEvent defaultSettingsModifiedEvent) {
        DefaultSettings defaultSettings = defaultSettingsRepository.findOne(1l);
        if (defaultSettings == null) {
            defaultSettings = new DefaultSettings();
        }
        defaultSettings.setAvatar(defaultSettingsModifiedEvent.getAvatar());
        defaultSettings.setBackground(defaultSettingsModifiedEvent.getBackground());
        defaultSettingsRepository.save(defaultSettings);
    }
}
